<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :loading="loading">
    <el-form v-loading="loading" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="80px">
      <el-form-item prop="type" :label="$t('menu.type')" size="mini">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="item in baseData.typeList" :key="item.val" :label="item.val">{{ $t(item.label) }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="name" :label="$t('menu.name')">
        <el-input v-model="dataForm.name" :placeholder="$t('menu.name')"></el-input>
      </el-form-item>
      <el-form-item prop="pid" :label="$t('menu.parentName')" class="menu-list">
        <!--父级选择框-->
        <uni-tree-select v-model="dataForm.pid" ref="parentTree" :data="parentTreeData" :treeParams="{defaultExpandAll:false}" />
      </el-form-item>
      <el-form-item v-if="showEntity['client']" prop="client" :label="$t('menu.client')">
        <el-select v-model="dataForm.client" :placeholder="$t('menu.client')">
          <el-option v-for="(item, index) in clientList" :key="index" :label="item.label" :value="item.val"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showEntity['url']" prop="url" :label="$t('menu.url')">
        <el-input v-model="dataForm.url" :placeholder="$t('menu.url')"></el-input>
      </el-form-item>
      <el-form-item v-if="showEntity['cssStyle']" prop="cssStyle" :label="$t('menu.cssStyle')">
        <el-input v-model="dataForm.cssStyle" :placeholder="$t('menu.cssStyle')"></el-input>
      </el-form-item>
      <el-form-item v-if="showEntity['frontColor']" prop="frontColor" :label="$t('menu.frontColor')">
        <el-input v-model="dataForm.frontColor" :placeholder="$t('menu.frontColor')"></el-input>
      </el-form-item>
      <el-form-item v-if="showEntity['bgColor']" prop="bgColor" :label="$t('menu.bgColor')">
        <el-input v-model="dataForm.bgColor" :placeholder="$t('menu.bgColor')"></el-input>
      </el-form-item>
      <el-form-item prop="sort" :label="$t('menu.sort')">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" :label="$t('menu.sort')">
        </el-input-number>
      </el-form-item>
      <el-form-item v-if="showEntity['permissions']" prop="permissions" :label="$t('menu.permissions')">
        <el-input v-model="dataForm.permissions" :placeholder="$t('menu.permissionsTips')"></el-input>
      </el-form-item>
      <el-form-item v-if="showEntity['icon']" prop="icon" :label="$t('menu.icon')" class="icon-list">
        <el-popover v-model="iconListVisible" ref="iconListPopover" placement="bottom-end" trigger="click" popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button v-for="(item, index) in iconList" :key="index" @click="iconListCurrentChangeHandle(item)" :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg" aria-hidden="true">
                  <use :xlink:href="`#${item}`"></use>
                </svg>
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-input v-model="dataForm.icon" :readonly="false" :placeholder="$t('menu.icon')">
          <el-button slot="append" icon="el-icon-search" v-popover:iconListPopover></el-button>
        </el-input>
      </el-form-item>
      <el-form-item prop="showFlag" :label="$t('menu.showFlag')">
        <el-radio-group v-model="dataForm.showFlag">
          <el-radio v-for="item in baseData.showFlagList" :key="item.val" :label="item.val">{{ $t(item.label) }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { getIconList } from '@/utils'
import staticData from './menu.json'
export default {
  data () {
    return {
      visible: false,
      loading: false,
      menuListVisible: false,
      iconList: [],
      iconListVisible: false,
      baseData: staticData,
      parentTreeData: [],
      initParams: {},
      dataForm: {
        id: '',
        type: 0, // 0 菜单、1：按钮、2 模块、3 目录
        name: '',
        // chname: '',
        // enname: '',
        // twname: '',
        pid: '0',
        parentName: '',
        url: '',
        permissions: '',
        sort: 0,
        icon: '',
        client: '',
        showFlag: 1,
        cssStyle: '',
        frontColor: '',
        bgColor: ''
      },
      pids: {}
    }
  },
  computed: {
    clientList: function () {
      return this.$getDictList(this.baseData.CODE_MENU_CLIENT, true)
    },
    /**
     * 处理 菜单类型的 控制显示
     */
    showEntity () {
      let entity = {}
      let showKeys = ''
      // 设置需要控制显示的字段 默认 不显示
      let keys = 'url,permissions,icon,cssStyle,frontColor,bgColor,client'
      for (let key of keys.split(',')) {
        entity[key] = false
      }

      // 菜单时 显示
      if (this.dataForm.type === 0) {
        showKeys = 'url,permissions,icon,cssStyle,frontColor,bgColor'
      }
      // 按钮时 显示
      if (this.dataForm.type === 1) {
        showKeys = 'permissions'
      }
      // 模块时显示
      if (this.dataForm.type === 2) {
        showKeys = 'icon,client'
      }
      // 目录时显示
      if (this.dataForm.type === 3) {
        showKeys = 'icon'
      }
      for (let key of showKeys.split(',')) {
        entity[key] = true
      }
      return entity
    },

    /**
     * 表单校验规则
     */
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    'dataForm.type' (val) {
      this.$refs['dataForm'].clearValidate()
    },
    'dataForm.pid' (val) {
      if (!val) { this.setDefaultHandle() }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm = {
          ...this.dataForm,
          ...this.initParams
        }
        this.iconList = getIconList()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          this.getSortInfo()
        }
      })
    },
    getSortInfo () {
      this.$http.get(`/sys/menu/getMenuSort/${this.dataForm.pid ? this.dataForm.pid : '0'}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.dataForm.sort = res.data.sort
      }).catch(() => { })
    },
    // 获取信息
    getInfo () {
      this.loading = true
      this.$http.get(`/sys/menu/${this.dataForm.id}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.dataForm.client = this.initParams.client
        this.pids.old = this.dataForm.pid
        if (this.dataForm.pid === '0') {
          this.setDefaultHandle()
        }
      }).catch(() => { })
    },
    // 上级菜单树, 设置默认值
    setDefaultHandle () {
      this.dataForm.pid = '0'
      this.dataForm.parentName = this.$t('menu.parentNameDefault')
    },
    // 图标, 选中
    iconListCurrentChangeHandle (icon) {
      this.dataForm.icon = icon
      this.iconListVisible = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // 处理设置为不显示字段的值
        for (var key in this.showEntity) {
          if (this.showEntity[key] === false) {
            this.dataForm[key] = ''
          }
        }
        // // 废弃的填充字段用name代替
        // this.dataForm.name = 'name'
        this.loading = true
        this.$http[!this.dataForm.id ? 'post' : 'put']('/sys/menu', this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.pids.new = this.dataForm.pid
              this.$emit('refreshDataList', this.pids)
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__menu {
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
